//
//  SearchResultPostViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/11.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "GKPhotoBrowser.h"

#import "PostListHeaderView.h"
#import "TT_BaseNaviView.h"
#import "PostEvaluateCell.h"
#import "PostEvaluateLookMoreCell.h"


#import "BA_CommunityInputTextView.h"

#import "PostSectionHeaderView.h"
#import "PostSectionFooterView.h"

#import "PostDetailViewController.h"
#import "QAPublishViewController.h"

#import "SearchResultPostViewController.h"

@interface SearchResultPostViewController ()<UITableViewDelegate, UITableViewDataSource, GKPhotoBrowserDelegate, BA_BottomInputViewDelegate, UITextViewDelegate>

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <CommonPostModel*>* dataArray;

@property (nonatomic, strong) BA_CommunityInputTextView *footView;

@end

@implementation SearchResultPostViewController

- (void)dealloc {
    
    
}

- (instancetype)initWithKeyWord:(NSString *)keyWord {
    
    self = [super init];
    
    if (self) {
        self.keyWord = keyWord;
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self.footView];
    [self.footView hideView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchCallBack:) name:@"searchNoti" object:nil];

    [self initView];
    [self refreshParam];
    [self request_data];

}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)initView {
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
}

-(void)searchCallBack:(NSNotification *)Noti {
    
    self.keyWord = [Noti.userInfo objectForKey:@"keyWord"];
    [self refreshParam];
    [self request_data];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [[IQKeyboardManager sharedManager] setEnable:NO];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [[IQKeyboardManager sharedManager] setEnable:YES];

    [self.footView hideView];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
}

-(BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
    return YES;
}

-(void)BA_BottomInputViewSendTextMessage:(NSString *)message {
    
    [self request_postEvaWithIndex:self.selectIndex AndContent:message];
}

- (void)request_data {
    
    [SVProgressHUD showWithStatus:@"正在请求数据"];
    [self request_postList];
}
    
- (void)showImageWithArray:(NSArray *)imageUrls index:(NSInteger)index {
    NSMutableArray *photos = [NSMutableArray new];
    
    [imageUrls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GKPhoto *photo = [GKPhoto new];
        photo.url = [NSURL URLWithString:obj];
        [photos addObject:photo];
    }];
    
    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:index];
    browser.showStyle = GKPhotoBrowserShowStyleNone;
    browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
    
    browser.delegate  = self;
    [browser showFromVC:self];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    //判断显示几个评论
    NSInteger count = 0;
    if (self.dataArray[section].sysPostChildList.count > 2) {
        count = 2;
    } else {
        count = self.dataArray[section].sysPostChildList.count;
    }
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return self.dataArray[section].itemHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.dataArray[indexPath.section].sysPostChildList[indexPath.row].itemHeight + 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (self.dataArray[section].sysPostChildList.count > 0) {
        return 45;
    } else {
        return 15;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    PostSectionHeaderView *sectionHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"PostSectionHeaderView"];
    sectionHeader.contentView.backgroundColor = UIColor.whiteColor;
    
    WEAKSELF
    sectionHeader.PostSectionHeaderViewBlock = ^(PostSectionHeaderActionType type, NSInteger index) {
      
        switch (type) {
            case PostSectionHeaderActionType_image:{
                if (weakSelf.dataArray[section].photoArray.count > 0) {
                    [weakSelf showImageWithArray:weakSelf.dataArray[section].photoArray index:index];
                }
            } break;
            case PostSectionHeaderActionType_eva:{
                
                weakSelf.selectIndex = section;
                [weakSelf.footView showView];
                [weakSelf.footView.textView becomeFirstResponder];
                
            } break;
            case PostSectionHeaderActionType_thumb:{
                
                weakSelf.selectIndex = section;
                [weakSelf request_postThumbWithIndex:section];

            } break;
            default:
                break;
        }
        
    };
    
    [sectionHeader fillWithModel:self.dataArray[section]];
    
    [sectionHeader addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        PostDetailViewController *vc = [[PostDetailViewController alloc] init];
        vc.pid = weakSelf.dataArray[section].pid;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    return sectionHeader;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    PostSectionFooterView*sectionFooter = [[NSBundle mainBundle] loadNibNamed:@"PostSectionFooterView" owner:nil options:nil].firstObject;
    sectionFooter.contentView.backgroundColor = UIColor.whiteColor;

    sectionFooter.mainTitleLab.text = [NSString stringWithFormat:@"查看共%lu条评论",(unsigned long)self.dataArray[section].replyCount];
    
    WEAKSELF
    [sectionFooter addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        PostDetailViewController *vc = [[PostDetailViewController alloc] init];
        vc.pid = weakSelf.dataArray[section].pid;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    return sectionFooter;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PostEvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostEvaluateCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillWithModel:self.dataArray[indexPath.section].sysPostChildList[indexPath.row]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row <2) {

    } else {

        PostDetailViewController *vc = [[PostDetailViewController alloc] init];
        vc.pid = self.dataArray[indexPath.section].pid;
        [self.navigationController pushViewController:vc animated:YES];
    }    
}

- (BA_CommunityInputTextView *)footView {
    if (_footView == nil) {
        _footView = [[BA_CommunityInputTextView alloc]init];
        _footView.delegate = self;
        _footView.textView.delegate = self;
    }
    return _footView;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostEvaluateCell" bundle:nil] forCellReuseIdentifier:@"PostEvaluateCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostEvaluateLookMoreCell" bundle:nil] forCellReuseIdentifier:@"PostEvaluateLookMoreCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostSectionHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"PostSectionHeaderView"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostSectionFooterView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"PostSectionFooterView"];

        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_data];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_data];
        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}

- (void)request_postList {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSDictionary *t = @{}.mutableCopy;

    //综合排序 1：综合 2：价格由高到低 3：价格由低到高  4热门
    [t setValue:self.keyWord forKey:@"searchName"];
    [t setValue:@"5" forKey:@"type"];
    [t setValue:[TTUserModel sharedObject].cityId forKey:@"sellerCityId"];
    [t setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SearchAll];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        
                        if (weakSelf.pageNum == 1) {
                            weakSelf.dataArray = @[].mutableCopy;
                            
                            if (list.count == 0) {
                                
                                [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_GoAsk btnTitle:@"去提问" didPressButton:^{
                                    
                                    QAPublishViewController *vc = [[QAPublishViewController alloc] init];
                                    [weakSelf.navigationController pushViewController:vc animated:YES];
                                }];
                                
                            }
                        }
                            
                        for (NSDictionary *dic in list) {
                            CommonPostModel *model = [CommonPostModel modelWithDictionary:dic];
                            
                            NSArray *sysMediaList = [dic valueForKey:@"sysMediaList"];
                            if ([sysMediaList isKindOfClass:[NSArray class]]) {
                                model.sysMediaList = @[].mutableCopy;
                                model.photoArray = @[].mutableCopy;
                                for (id mediaDic in sysMediaList) {
                                    
                                    CommonMediaModel *mediaModel = [[CommonMediaModel alloc] init];
                                    if ([mediaDic isKindOfClass:[NSDictionary class]]) {
                                        NSDictionary *media = mediaDic;
                                        mediaModel = [CommonMediaModel modelWithDictionary:media];
                                        [model.photoArray addObject:mediaModel.url];

                                    }
                                    
                                    if ([mediaDic isKindOfClass:[NSString class]]) {
                                        NSString *media = mediaDic;
                                        mediaModel.url = media;
                                        [model.photoArray addObject:media];
                                    }
                                    
                                    [model.sysMediaList addObject:mediaModel];
                                }
                            }
                            
                            NSArray *sysPostChildList = [dic valueForKey:@"sysPostChildList"];
                            if ([sysPostChildList isKindOfClass:[NSArray class]]) {
                                
                                //最多展示两条，所以就不需要那么多循环  省点时间
                                if (sysPostChildList.count > 2) {
                                    sysPostChildList = [sysPostChildList subarrayWithRange:NSMakeRange(0, 2)];
                                }
                                
                                model.sysPostChildList = @[].mutableCopy;
                                for (NSDictionary * evaDic in sysPostChildList) {
                                    CommunityEvaModel *evaModel = [CommunityEvaModel modelWithDictionary:evaDic];
                                    
                                    //富文本
                                    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:%@",evaModel.userNickName,evaModel.content]];
                                    NSRange nameRange = NSMakeRange(0, evaModel.userNickName.length);
                                    NSRange contentRange = NSMakeRange(evaModel.userNickName.length + 1,evaModel.content.length);
                                    // 设置字体大小
                                    [attrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:nameRange];
                                    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:contentRange];
                                    evaModel.evaContentAttr = attrStr;
                                    
                                    evaModel.content = [NSString stringWithFormat:@"%@:%@",evaModel.userNickName,evaModel.content];

                                    CGFloat itemHeight = [Utilities getStringHeightWithText:evaModel.content font:[UIFont systemFontOfSize:13] viewWidth:(TTScreenWidth-48)];
                                    
                                    if (itemHeight > 30) {
                                        evaModel.itemHeight = 30;
                                    } else {
                                        evaModel.itemHeight = [Utilities getStringHeightWithText:evaModel.content font:[UIFont systemFontOfSize:13] viewWidth:(TTScreenWidth-48)];
                                    }
                                    
                                    [model.sysPostChildList addObject:evaModel];
                                }
                            }
                            
                            //自定义处理区域
                            model.content = [NSString stringWithFormat:@"【%@】%@",model.themeTitle,model.title];
                            model.textHeight = [Utilities getStringHeightWithText:model.content font:[UIFont systemFontOfSize:14] viewWidth:(TTScreenWidth - 28)];
                            
                            if (model.sysMediaList.count > 0) {
                                model.imageHeight = (TTScreenWidth - 32)/3 + 10;
                            } else {
                                model.imageHeight = CGFLOAT_MIN;
                            }
                            model.itemHeight = [PostSectionHeaderView calculateHWithModel:model];
                            
                            [weakSelf.dataArray addObject:model];
                        }
                            
                    } else {
                        
                    }
                    [weakSelf.tableview reloadData];
                }
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {

        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}

- (void)request_postEvaWithIndex:(NSInteger)index AndContent:(NSString *)content {
        
    CommonPostModel *model = self.dataArray[index];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:content forKey:@"content"];

    [dic setValue:model.pid forKey:@"baseId"];
    [dic setValue:@"2" forKey:@"level"];
    [dic setValue:model.source forKey:@"source"];
    [dic setValue:model.userId forKey:@"userId"];
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [dic setValue:@"1" forKey:@"mold"];

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"1" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在发布评论"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.footView.textView.text = @"";
                [weakSelf.view endEditing:YES];
                
                [weakSelf request_data];
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}


- (void)request_postThumbWithIndex:(NSInteger)index {
        
    CommonPostModel *model = self.dataArray[index];

    NSMutableDictionary *dic = @{}.mutableCopy;

    //点赞帖子
    [dic setValue:model.pid forKey:@"baseId"];
    [dic setValue:@"1" forKey:@"level"];
    [dic setValue:model.source forKey:@"source"];
    [dic setValue:model.userId forKey:@"userId"];

    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    if (model.isZan.length > 0) {
        [dic setValue:@"5" forKey:@"mold"];
        [dic setValue:model.isZan forKey:@"otherId"];
    } else {
        [dic setValue:@"2" forKey:@"mold"];
    }

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"1" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSString *isZan = [data valueForKey:@"data"];
                if ([isZan isKindOfClass:[NSString class]]) {
                    
                    model.isZan = isZan;
                    if (isZan.length > 0) {
                        model.likes++;
                    } else {
                        model.likes--;
                    }
                    
                    [weakSelf.tableview reloadData];
                }
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}
@end
